package com.jrx.anytxn.transaction.job.paph.config;

import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.FileUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.config.PaphSftpConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.IPaphFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.List;

/**
 * 平安普惠影像回传文件打包上传
 *
 * @author liuyang
 * @date 2021-3-17
 */
@Configuration
@EnableConfigurationProperties({PaphSftpConfig.class, PaphFileConfig.class})
public class PostBackImageFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(PostBackImageFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IPaphFileService paphFileService;

    @Autowired
    private PaphSftpConfig paphSftpConfig;

    @Autowired
    private PaphFileConfig paphFileConfig;

    @Autowired
    private IOrganizationTableService organizationTableService;


    @Bean
    public Job postBackImageFileJob() {
        return jobBuilderFactory.get("postBackImageFileJob")
                .start(compressPreContFileStep())
                .next(uploadPreContFileStep())
                .build();
    }

    @Bean
    public Step compressPreContFileStep() {
        return stepBuilderFactory.get("compressPreContFileStep")
                .tasklet(compressPreContFileTasklet())
                .build();
    }

    @Bean
    public Step uploadPreContFileStep() {
        return stepBuilderFactory.get("uploadPreContFileStep")
                .tasklet(uploadPreContFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet compressPreContFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("=====平安普惠文件打包处理开始=====");
            paphFileService.compressPreContFile(paphFileConfig.getBackImagePath());
            logger.info("=====平安普惠文件打包处理完成=====");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    @StepScope
    public Tasklet uploadPreContFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("=====平安普惠文件上传处理开始=====");

            // 查询机构信息
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String todayStr = DateUtils.format(org.getToday(), DateUtils.DATE_PATTERN_ANOTHER);
            String businessDateStr = DateUtils.format(org.getNextProcessingDate(), DateUtils.DATE_PATTERN_ANOTHER);

            //1 获取连接
            SftpUtils.sftpConnect(paphSftpConfig.getUsername(), paphSftpConfig.getPassword(), paphSftpConfig.getHost(), paphSftpConfig.getPort());

            //2 创建目录
            SftpUtils.createDir(paphSftpConfig.getUploadPath());

            //3 上传tar包
            StringBuilder tarPathSb = new StringBuilder();
            tarPathSb.append(paphFileConfig.getBackImagePath()).append(File.separator).append(org.getTenantId()).append(File.separator).append(todayStr);
            String tarPath = tarPathSb.toString();

            // 获取提前结清证明和借款合同的压缩包
            List<File> files = FileUtils.findFiles(tarPath);
            for (File file : files) {
                String fileName = file.getName();
                if (fileName.endsWith(".tar")) {
                    if (fileName.lastIndexOf(TransBizConstant.PA_ADVSTLE) > -1) {
                        // 上传提前结清证明
                        SftpUtils.sftpUpload(file);
                        logger.info("平安普惠影像回传的提前结清证明tar文件[{}]上传完成。", file.getAbsolutePath());
                        continue;
                    }
                    if (fileName.lastIndexOf(TransBizConstant.PA_LOANINFO) > -1) {
                        // 上传借款合同
                        SftpUtils.sftpUpload(file);
                        logger.info("平安普惠影像回传的借款合同tar文件[{}]上传完成。", file.getAbsolutePath());
                        continue;
                    }
                }
            }

            //4 上传OK文件
            StringBuilder okFilePathSb = new StringBuilder();
            okFilePathSb.append(tarPathSb).append(File.separator).append(TransBizConstant.LS_BANK).append(TransBizConstant.PA_CUSTINFOBACKTOPA).append("-").append(businessDateStr).append("OK").append(".txt");
            String okFilePath = okFilePathSb.toString();
            if (FileUtils.isExists(okFilePath)) {
                SftpUtils.sftpUpload(new File(okFilePath));
                logger.info("平安普惠影像回传的ok文件[{}]上传完成。", okFilePath);
            } else {
                logger.error("平安普惠影像回传的ok文件[{}]不存在。", okFilePath);
                throw new TxnException("平安普惠影像回传的ok文件[" + okFilePath + "]不存在。");
            }

            //5 上传md5文件
            StringBuilder md5FilePathSb = new StringBuilder();
            md5FilePathSb.append(tarPathSb).append(File.separator).append(TransBizConstant.LS_BANK).append(TransBizConstant.PA_CUSTINFOBACKTOPA).append("-").append(businessDateStr).append("OK").append(".md5");
            String md5FilePath = md5FilePathSb.toString();
            if (FileUtils.isExists(md5FilePath)) {
                SftpUtils.sftpUpload(new File(md5FilePath));
                logger.info("平安普惠影像回传的md5文件[{}]上传完成。", md5FilePath);
            } else {
                logger.error("平安普惠影像回传的md5文件[{}]不存在。", md5FilePath);
                throw new TxnException("平安普惠影像回传的md5文件[" + md5FilePath + "]不存在。");
            }

            //6 关闭连接
            SftpUtils.disSftpConnect();
            logger.info("=====平安普惠文件上传处理完成=====");
            return RepeatStatus.FINISHED;
        };
    }
}
